<template>
  <el-drawer v-model="drawer" :close-on-click-modal="false" :direction="direction">
    <template #header>
      <h4>添加房间</h4>
    </template>
    <template #default>
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto" label-position="top">
        <el-form-item label="房型" prop="roomType">
          <el-input v-model="ruleForm.roomType" placeholder="请输入房型"/>
        </el-form-item>
        <el-form-item label="所属酒店" prop="hotelName">
          <el-select v-if="!props.fixedHotel" v-model="ruleForm.hotelName" placeholder="请选择酒店" style="width: 100%">
            <el-option v-for="item in hotelList" :key="item.hotelName" :label="item.hotelName" :value="item.hotelName"/>
          </el-select>
          <el-input v-else v-model="ruleForm.hotelName" disabled />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model.number="ruleForm.price" placeholder="请输入价格"/>
        </el-form-item>
        <el-form-item label="可用数量" prop="availableCount">
          <el-input-number v-model="ruleForm.availableCount" :min="0" placeholder="请输入可用数量"/>
        </el-form-item>
        <el-form-item label="含早" prop="breakfast">
          <el-radio-group v-model="ruleForm.breakfast">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片URL" prop="imageUrl">
          <el-input v-model="ruleForm.imageUrl" placeholder="请输入图片URL"/>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { createRoom } from '@/api/room'
import { getHotelList } from '@/api/hotel'

interface Props {
  fixedHotel?: string
}

const props = withDefaults(defineProps<Props>(), {
  fixedHotel: ''
})

const emit = defineEmits(['refresh'])

interface RuleForm {
  roomType: string
  hotelName: string
  price: number
  availableCount: number
  breakfast: string
  imageUrl: string
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  roomType: '',
  hotelName: '',
  price: null,
  availableCount: 1,
  breakfast: '0',
  imageUrl: ''
})
const hotelList = ref([])

const drawer = ref(false)
const direction = ref<'rtl' | 'ltr' | 'ttb' | 'btt'>('rtl')

const rules = reactive<FormRules<RuleForm>>({
  roomType: [{ required: true, message: '请输入房型', trigger: 'blur' }],
  hotelName: [{ required: true, message: '请选择酒店', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  availableCount: [{ required: true, message: '请输入可用数量', trigger: 'change' }]
})

// 监听fixedHotel属性变化
watch(() => props.fixedHotel, (newVal) => {
  if (newVal) {
    ruleForm.hotelName = newVal
  }
}, { immediate: true })

const submitForm = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      // 确保数值字段是正确的格式
      const formData = {
        ...ruleForm,
        // 确保数值类型字段是数字
        price: Number(ruleForm.price),
        availableCount: Number(ruleForm.availableCount),
        // 确保breakfast是字符串类型
        breakfast: String(ruleForm.breakfast)
      };
      
      console.log('提交新增房间数据:', formData);
      
      createRoom(formData).then(res => {
        console.log('新增房间响应:', res);
        
        const result = res.data;
        if (result && result.code === 200) {
          ElMessage.success('添加成功')
          handleClose()
          emit('refresh')
        } else {
          ElMessage.error(result?.msg || '添加失败')
        }
      }).catch(error => {
        console.error('添加房间错误:', error);
        ElMessage.error('网络错误，添加房间失败');
      });
    }
  })
}

const handleClose = () => {
  drawer.value = false
  
  // 重置表单
  ruleForm.roomType = ''
  ruleForm.price = null
  ruleForm.availableCount = 1
  ruleForm.breakfast = '0'
  ruleForm.imageUrl = ''
  
  // 如果有固定酒店，重置为固定酒店名
  if (props.fixedHotel) {
    ruleForm.hotelName = props.fixedHotel
  } else {
    ruleForm.hotelName = ''
  }
}

const open = () => {
  drawer.value = true
  
  // 如果有固定酒店，设置为固定酒店名
  if (props.fixedHotel) {
    ruleForm.hotelName = props.fixedHotel
  } else {
    // 获取酒店列表
    getHotelList({}).then(res => {
      console.log('获取酒店列表响应:', res);
      const result = res.data;
      if (result && result.code === 200 && result.data) {
        hotelList.value = result.data;
      } else {
        ElMessage.warning('获取酒店列表失败');
      }
    });
  }
}

defineExpose({ open })
</script>
